//
//  LFBReadCarouselContentView.m
//  ONE
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LFBReadCarouselContentView.h"
#import "LFBNetTool.h"
#import "LFBReadCarouselContentCell.h"
#import "LFBSerialListModel.h"
#import "LFBReadSerialModel.h"

@interface LFBReadCarouselContentView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

/** 左上角关闭按钮 */
@property (nonatomic, strong) UIButton *closeButton;

/** 轮播图内容集合视图 */
@property (nonatomic, strong) UICollectionView *collectionView;

/** 集合视图高度约束 */
@property (nonatomic, strong) MASConstraint *collectionViewHeightConstraint;

@end

/** 重用头部标识 */
NSString *kCollectionViewReuseHeaderID = @"LFBCollectionViewReuseHeaderID";

/** 头部高度 */
NSInteger kCollectionViewHeaderHeight = 50;

@implementation LFBReadCarouselContentView
{
    /** 列表数据源 */
    LFBSerialListModel *serialListModel;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self createCarousCView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createCarousCView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self createCarousCView];
    }
    return self;
}

#pragma mark --创建轮播图内容视图
- (void)createCarousCView
{
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    if (_closeButton) {
        return;
    }
    
    self.backgroundColor = [UIColor whiteColor];
    
    // 初始化布局对象
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.itemSize = [LFBReadCarouselContentCell cellSize];
    layout.minimumInteritemSpacing = 13;
    layout.minimumLineSpacing = 10;
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH - 24 * 2, kCollectionViewHeaderHeight);
    
    // 初始化轮播图内容集合视图
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    // 注册cell
    [_collectionView registerClass:[LFBReadCarouselContentCell class] forCellWithReuseIdentifier:kLFBCarouselCCellID];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCollectionViewReuseHeaderID];
    [self addSubview:_collectionView];
    [_collectionView makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        _collectionViewHeightConstraint = make.height.equalTo(kCollectionViewHeaderHeight);
        make.left.equalTo(self).offset(24);
        make.right.equalTo(self).offset(-24);
    }];
    
    // 初始化左上角关闭按钮
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _closeButton.backgroundColor = [UIColor whiteColor];
    [_closeButton setImage:[UIImage imageNamed:@"close_normal"] forState:UIControlStateNormal];
    [_closeButton setImage:[UIImage imageNamed:@"close_highlighted"] forState:UIControlStateHighlighted];
    
    [_closeButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_closeButton];
    [_closeButton makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(44);
        make.left.equalTo(self).offset(3);
        make.top.equalTo(self).offset(20);
    }];
}

#pragma mark --刷新数据方法
- (void)updateView
{
    NSInteger rowNumber = ceilf(serialListModel.list.count / 5.0);
    NSInteger height = kCollectionViewHeaderHeight + [LFBReadCarouselContentCell cellSize].height * rowNumber + ((UICollectionViewFlowLayout *)_collectionView.collectionViewLayout).minimumLineSpacing * (rowNumber - 1);
    _collectionViewHeightConstraint.equalTo(height);
    [_collectionView reloadData];
}

// 显示集合视图
- (void)show
{
    self.alpha = 0;
    // UIWindow数组中最后调用makeKeyAndVisible方法的UIWindow对象
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self getData];
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

// 关闭集合视图
- (void)dismiss
{
    [self dismissWithCompleted:NULL];
}

- (void)dismissWithCompleted:(void (^)())completedBlock
{
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        _collectionViewHeightConstraint.equalTo(kCollectionViewHeaderHeight);
        serialListModel = nil;
        if (completedBlock) {
            completedBlock();
        }
    }];
}

#pragma mark --网络请求
- (void)getData
{
    [LFBNetTool getNetWithURL:[NSString stringWithFormat:LYLApiSerialList, _serialModel.serial_id] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue] == 0) {
            NSDictionary *data = result[@"data"];
                LFBSerialListModel *listModel = [[LFBSerialListModel alloc] initWithDic:data];
            serialListModel = listModel;
            [self updateView];
        }
    } Failure:^(NSError *error) {
        
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return serialListModel.list.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCollectionViewReuseHeaderID forIndexPath:indexPath];
    if (view.subviews.count <= 0) {
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = _serialModel.title;
        titleLabel.font = FontWithSize(18);
        titleLabel.textColor = LYLLightBlackTextColor;
        titleLabel.textAlignment = 1;
        [view addSubview:titleLabel];
        [titleLabel makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(view);
        }];
        
        UIView *line = [UIView new];
        line.backgroundColor = LYLSeparatorColor;
        [view addSubview:line];
        [line makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(0.5);
            make.left.bottom.right.equalTo(view);
        }];
    }
    
    return view;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LFBReadCarouselContentCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kLFBCarouselCCellID forIndexPath:indexPath];
    
    LFBReadSerialModel *serial = serialListModel.list[indexPath.row];
    cell.numberLabel.text = serial.number;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    // 跳转
    if (_didSelectedSerial) {
        _didSelectedSerial(serialListModel.list[indexPath.row]);
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
